import 'dart:async';
import 'dart:io';

import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ladder_cash/app/app.dart';
import 'package:ladder_cash/app/com/http/http_request.dart';
import 'package:ladder_cash/app/com/plugin/common_plugin.dart';
import 'package:ladder_cash/app/key_mix.dart';
import 'package:ladder_cash/app/page/login/guide_page.dart';
import 'package:ladder_cash/app/page/login/login_page.dart';
import 'package:ladder_cash/config/super_theme.dart';

import 'package:ladder_cash/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:liuxlcommon/util/sp_utils.dart';
import 'package:ladder_cash/app/com/service/reported_data_service.dart';
import 'package:ladder_cash/app/com/view/common_view.dart';
import 'package:ladder_cash/app/page/home/home_page.dart';
import 'package:liuxlcommon/util/string_utils.dart';
import '../../../Global.dart';
import '../../../gen/assets.gen.dart';
import '../../../library/src/logger.dart';
import '../component/common.dart';
import 'login_logic.dart';

class LaunchPage extends StatefulWidget {
  final Function(Locale) switchLanguage;
  LaunchPage({super.key, required this.switchLanguage});

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LaunchPage>
    with SingleTickerProviderStateMixin {
  bool isfrist = false;
  bool isOnLoad = false;
  bool isAgree = false;
  bool initLanguge = false;

  @override
  void didUpdateWidget(covariant LaunchPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    // precacheImage(const AssetImage(Assets.pcLargebg), context);
  }

  @override
  void initState() {
    super.initState();
    Get.delete<HomePage>();
    var widgetsBinding = WidgetsBinding.instance;
    widgetsBinding.addPostFrameCallback((callback) async {
      if (Platform.isIOS) {
        if (!await checkInternetConnection(isNetwork: true)) {}
        getStart();
      } else {
        // await HttpRequest().setDynamicDomainAndroid();
      }
    });
  }

  getStart() async {
    if (await HttpRequest().setDynamicDomain()) {
      initLanguage();
      if (!isfrist) {
        isfrist = true;
        if (Platform.isAndroid) {
          // await platformAndroid();
        } else {
          await platformIos();
        }
      }
      Timer(const Duration(seconds: 1), () async {
        isOnLoad = true;
        next();
      });
    }
    ;
  }
  // platformAndroid() async {
  //   isAgree = SpUtils().getStorage1("loginAgreenDialog", false);
  //   initLanguge = true;
  //   if (isAgree) {
  //     next();
  //   } else {
  //     CommonView.loginAgreenDialog(onConfirm: () async {
  //       SpUtils().setStorage("loginAgreenDialog", true);
  //       Get.back();
  //       await ReportedDataService().checkPermission();
  //       isAgree = true;
  //       next();
  //     });
  //   }
  // }

  platformIos() async {
    await CommonPlugin.getWaitIdea();
    await ReportedDataService().checkPermission(goToSetting: false);
    isAgree = true;
    next();
  }

  next() async {
    if (isAgree && isOnLoad && initLanguge) {
      await App.init2();
      // if (App.localeEn) {
      //   Get.offAll(const c.HomePage());
      // } else {
      if (SpUtils().getStorage1("isGuide", true)) {
        SpUtils().setStorage("isGuide", false);
        Get.offAll(GuidePage());
        // Get.offAll( HomePage());
      } else {
        Get.offAll(HomePage());
      }

      return;
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // precacheImage(const AssetImage(Assets.bgABg1), context);
    if (SpUtils().getStorage1("isGuide", true)) {}
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        // body: Image.asset(Assets.molopNewStartpage,
        body: Container(
      width: Global.width,
      height: Global.height,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('${Assets.splash.splash9527bg.path}'),
          fit: BoxFit.cover,
        ),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            children: [
              SizedBox(
                height: 126,
              ),
              LinearProgressIndicator(
                valueColor:
                    AlwaysStoppedAnimation<Color>(SuperTheme.primary), // 自定义颜色
                backgroundColor: SuperTheme.lightBgPrimary, // 自定义背景颜色
                minHeight: 3, // 自定义高度
              ),
              SizedBox(
                height: 30,
              ),
              Image.asset(
                "${Assets.img.logo.path}",
                width: 82,
                height: 82,
              ),
              const SizedBox(
                height: 12,
              ),
              Text(
                S.current.appName,
                style: const TextStyle(
                    fontFamily: 'italic',
                    fontWeight: FontWeight.w700,
                    fontSize: 26),
              ),
              const SizedBox(
                height: 12,
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 53),
                child: Text(S.current.splashContent,
                    style:
                        TextStyle(fontSize: 14, fontWeight: FontWeight.w300)),
              )
            ],
          ),
          Container(
            height: 53,
            width: Global.width,
            alignment: Alignment.center,
            margin: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 44),
            child: commonBtn(S.current.tye_again, callback: () {
              getStart();
            }),
          ),
        ],
      ),
    ));
  }

  initLanguage() async {
    var data = await HttpRequest()
        .get('/service/login/login-init'.hx, null, autoToast: false);
    if (data != null) {
      if (StringUtils.isNotEmpty(data['privacy'.hx])) {
        App.privacy = data['privacy'.hx];
      }
      App.area_code = data['area_code'];
      if (data['isSetPop'.hx] == 2) {
        isPermissionsDialog = true;
      }
      if (data['isNeedPop'.hx] == 1) {
        isPermissionsDialog = true;
        S.load(const Locale('en'));
        App.localeCode = "en";
        Locale('en', '');
        widget.switchLanguage(Locale('en', ''));
        // 更新应用的语言环境
      } else {
        S.load(const Locale('es'));

        widget.switchLanguage(Locale('es', ''));
        App.localeCode = "es";
      }
      CommonPlugin.initFB(data);

      initLanguge = true;
      next();
    } else {
      await Future.delayed(const Duration(seconds: 1));
      await initLanguage();
    }
  }

  @override
  void dispose() {
    Get.delete<LoginLogic>();
    super.dispose();
  }
}
